package com.tianma.celue.service.impl;

import com.tianma.celue.componet.CaCheTemplete;
import com.tianma.celue.componet.Constants;
import com.tianma.celue.dao.UserMapper;
import com.tianma.celue.domain.User;
import com.tianma.celue.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

/**
 * @author lgc
 * @createDate 2020/6/29 - 16:07
 */
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    CaCheTemplete caCheTemplete;


    @Override
    public User getUserById(Integer id) {
        redisTemplate.setKeySerializer( new StringRedisSerializer());
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(User.class));

        User user =(User) redisTemplate.opsForValue().get(Constants.USER_KEY + id);
        if (null == user){
            synchronized (this){
                user =(User)  redisTemplate.opsForValue().get(Constants.USER_KEY+ id);
                if (null == user){
                    System.out.println("查询数据库");
                    user = userMapper.getUserById(id);
                    redisTemplate.opsForValue().set(Constants.USER_KEY+ id,user);
                }
            }
        }
     return user;
    }

    @Override
    public User getUserByIdTemplate(Integer id) {
        User user = caCheTemplete.loadCache(Constants.USER_KEY + id, () -> {
            return userMapper.getUserById(id);
        });
        return user;
    }
}
